<template>
  <div class="common-layout">
    <!-- <el-container>
      <el-header style="min-height: 6vh; margin-top: 1vh">
        <div class="header-content common-div-card">
          <el-form :model="headerSearchForm" label-width="auto" :inline="true">
            <el-form-item label="时间范围">
              <div class="date-select">
                <el-date-picker v-model="headerSearchForm.start" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
                <span>-</span>
                <el-date-picker v-model="headerSearchForm.end" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button type="primary" @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main> -->
    <div class="table-container common-div-card">
      <el-table
        :data="tableData"
        :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center', border: '1px solid #e1e1f1' }"
        :cell-style="{ textAlign: 'center' }"
        v-loading="loading"
        ref="tableRef"
        :show-overflow-tooltip="true"
        element-loading-text="加载中..."
        :span-method="objectSpanMethod"
        style="width: 100%"
        show-summary
        border
      >
        <template v-for="(col, index) in columns" :key="index">
          <el-table-column :label="col.label" :prop="col.prop" :fixed="index < 3 ? 'left' : false" :width="index < 3 ? 120 : undefined">
            <template v-if="col.children && col.children.length">
              <el-table-column v-for="(subCol, subIndex) in col.children" :key="subIndex" :label="subCol.label" :prop="subCol.prop" />
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <!-- <div class="pagination common-div-card">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div> -->
    <!-- </el-main>
    </el-container> -->
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted, nextTick, defineComponent } from 'vue';
  import { ElMessage, ElMessageBox, ElTable, TabsPaneContext } from 'element-plus';
  import dayjs from 'dayjs';
  import { contractTrackingApi } from '/@/api/report/contractTracking';

  const getSpanMap = (data: any) => {
    const productMap = new Map(); // 品名维度的合并信息
    const surfaceMap = new Map(); // 表面等级维度的合并信息
    const customerMap = new Map(); // 汽车客户维度的合并信息

    data.forEach((item: any, index: any) => {
      // 构造层级唯一键
      const productKey = item.orderTypes;
      const surfaceKey = `${productKey}_${item.sufaceClass}`;
      const customerKey = `${surfaceKey}_${item.clientName}`;

      // 统计品名的合并行数
      if (!productMap.has(productKey)) {
        productMap.set(productKey, { start: index, count: 1 });
      } else {
        productMap.get(productKey).count++;
      }

      // 统计表面等级的合并行数
      if (!surfaceMap.has(surfaceKey)) {
        surfaceMap.set(surfaceKey, { start: index, count: 1 });
      } else {
        surfaceMap.get(surfaceKey).count++;
      }

      // 统计汽车客户的合并行数
      if (!customerMap.has(customerKey)) {
        customerMap.set(customerKey, { start: index, count: 1 });
      } else {
        customerMap.get(customerKey).count++;
      }
    });

    return { productMap, surfaceMap, customerMap };
  };

  // 表格数据
  const tableData = ref<any>([]);
  const spanMap = ref(getSpanMap(tableData.value));
  const tableRef = ref<InstanceType<typeof ElTable>>();
  const loading = ref(false);

  const columns = ref([
    { label: '品名', prop: 'orderTypes' },
    { label: '表面等级', prop: 'sufaceClass' },
    { label: '汽车钢客户', prop: 'clientName' },
    {
      label: '合计',
      children: [
        { label: '待过', prop: 'sum0' },
        { label: '原料库', prop: 'sum1' },
        { label: '轧后', prop: 'sum2' },
        { label: '精整', prop: 'sum3' },
        { label: '订货重量', prop: 'sum4' },
        { label: '准发欠量', prop: 'sum5' },
      ],
    },
    {
      label: `${Number(dayjs().format('MM')) - 2}月`,
      children: [
        { label: '待过', prop: 'mon10' },
        { label: '原料库', prop: 'mon11' },
        { label: '轧后', prop: 'mon12' },
        { label: '精整', prop: 'mon13' },
        { label: '订货重量', prop: 'mon14' },
        { label: '准发欠量', prop: 'mon15' },
      ],
    },
    {
      label: `${Number(dayjs().format('MM')) - 1}月`,
      children: [
        { label: '待过', prop: 'mon20' },
        { label: '原料库', prop: 'mon21' },
        { label: '轧后', prop: 'mon22' },
        { label: '精整', prop: 'mon23' },
        { label: '订货重量', prop: 'mon24' },
        { label: '准发欠量', prop: 'mon25' },
      ],
    },
    {
      label: `${dayjs().format('MM')}月`,
      children: [
        { label: '待过', prop: 'mon30' },
        { label: '原料库', prop: 'mon31' },
        { label: '轧后', prop: 'mon32' },
        { label: '精整', prop: 'mon33' },
        { label: '订货重量', prop: 'mon34' },
        { label: '准发欠量', prop: 'mon35' },
      ],
    },
  ]);
  // 合并单元格
  const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
    const { productMap, surfaceMap, customerMap } = spanMap.value;

    // 品名列（第1列）
    if (columnIndex === 0) {
      const productKey = row.orderTypes;
      const product = productMap.get(productKey);
      if (product && rowIndex === product.start) {
        return { rowspan: product.count, colspan: 1 };
      } else {
        return { rowspan: 0, colspan: 0 };
      }
    }

    // 表面等级列（第2列）
    if (columnIndex === 1) {
      const productKey = row.orderTypes;
      const surfaceKey = `${productKey}_${row.sufaceClass}`;
      const surface = surfaceMap.get(surfaceKey);
      if (surface && rowIndex === surface.start) {
        return { rowspan: surface.count, colspan: 1 };
      } else {
        return { rowspan: 0, colspan: 0 };
      }
    }

    // 汽车客户列（第3列）
    if (columnIndex === 2) {
      const productKey = row.orderTypes;
      const surfaceKey = `${productKey}_${row.sufaceClass}`;
      const customerKey = `${surfaceKey}_${row.clientName}`;
      const customer = customerMap.get(customerKey);
      if (customer && rowIndex === customer.start) {
        return { rowspan: customer.count, colspan: 1 };
      } else {
        return { rowspan: 0, colspan: 0 };
      }
    }

    // 其他列默认不合并
    return { rowspan: 1, colspan: 1 };
  };

  interface SearchForm {
    start: string;
    end: string;
  }
  // 表单数据
  const headerSearchForm = reactive<SearchForm>({
    start: '',
    end: '',
  });

  // 分页数据
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取表格数据
  const fetchTableData = async () => {
    loading.value = true;
    try {
      const res = await contractTrackingApi.orderRep();
      tableData.value = res.data.data
        .filter((item: any) => item.orderTypes !== '合计')
        .map((item: any) => {
          const curItem = { ...item };
          for (const key in curItem) {
            if (['orderTypes', 'sufaceClass', 'clientName', 'mon1List', 'mon2List', 'mon3List'].includes(key)) continue;
            // if (key != 'orderTypes' || key != 'sufaceClass' || key != 'clientName')
            curItem[key] = curItem[key].toFixed(0);
          }
          return curItem;
        });
      // tableData.value = tableData.value
      if (tableData.value.length > 0) spanMap.value = getSpanMap(tableData.value);
      loading.value = false;
    } catch (error) {
      loading.value = false;
      console.error(error);
      ElMessage.error('获取数据失败');
    }
  };

  // 查询方法
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchTableData();
  };

  const dateReset = () => {
    headerSearchForm.start = dayjs().format('YYYY-MM-DD 00:00:00');
    headerSearchForm.end = dayjs().format('YYYY-MM-DD 23:59:59');
  };

  // 重置方法
  const handleReset = () => {
    dateReset();
    handleSearch();
  };

  // 分页大小变化
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    fetchTableData();
  };

  // 页码变化
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchTableData();
  };

  // 生命周期钩子
  onMounted(() => {
    fetchTableData();
  });

  onUnmounted(() => {});

  // 合计行计算
  function calcTotal(data: any) {
    const total = {
      totalWait: 0,
      totalSource: 0,
      totalRolled: 0,
      totalFinish: 0,
      totalOrder: 0,
      totalDiff: 0,
      mblWait: 0,
      mblSource: 0,
      mblRolled: 0,
      mblFinish: 0,
      mblOrder: 0,
      mblDiff: 0,
      lmWait: 0,
      lmSource: 0,
      lmRolled: 0,
      lmFinish: 0,
      lmOrder: 0,
      lmDiff: 0,
      cmWait: 0,
      cmSource: 0,
      cmRolled: 0,
      cmFinish: 0,
      cmOrder: 0,
      isTotal: true,
    };
    data.forEach((item: any) => {
      total.totalWait += item.totalWait;
      total.totalSource += item.totalSource;
      total.totalRolled += item.totalRolled;
      total.totalFinish += item.totalFinish;
      total.totalOrder += item.totalOrder;
      total.totalDiff += item.totalDiff;
      total.mblWait += item.mblWait;
      total.mblSource += item.mblSource;
      total.mblRolled += item.mblRolled;
      total.mblFinish += item.mblFinish;
      total.mblOrder += item.mblOrder;
      total.mblDiff += item.mblDiff;
      total.lmWait += item.lmWait;
      total.lmSource += item.lmSource;
      total.lmRolled += item.lmRolled;
      total.lmFinish += item.lmFinish;
      total.lmOrder += item.lmOrder;
      total.lmDiff += item.lmDiff;
      total.cmWait += item.cmWait;
      total.cmSource += item.cmSource;
      total.cmRolled += item.cmRolled;
      total.cmFinish += item.cmFinish;
      total.cmOrder += item.cmOrder;
    });
    tableData.value.push(total);
  }
</script>
<style lang="less" scoped>
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  @box-shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.12);
  @border: 1px solid #dcdfe6;

  .common-div-card {
    box-shadow: @box-shadow;
    transition: 0.3s;
    border-radius: @border-radius;
    border: @border;

    // 悬停状态
    &:hover {
      box-shadow: @box-shadow-hover;
    }
  }

  .common-layout {
    width: 99.5%;
    background-color: #fff !important;
    min-height: 88vh;
    padding: 0.5rem;
  }

  .header-content {
    display: flex;
    justify-content: flex-start;
    padding: 1rem 1rem 0 1rem;
    // min-height: 8vh;
    // .el-form {
    //   margin-top: 2vh;
    // }
  }

  .date-select {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    gap: 12px;
  }

  .table-container {
    padding: 0.5rem;
    height: 85vh;

    :deep(.el-table) {
      height: 100%;
      max-width: 100%;
    }
  }

  .pagination {
    margin-top: 2vh;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
  }

  .warning-row {
    background-color: '#ffe6e6';
  }
</style>
